package com.baor.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.HolderWithdrawalStatisticsDao;
import com.baor.dao.WorkorderDao;
import com.baor.domain.CustomerVO;
import com.baor.domain.EquipmentVO;
import com.baor.domain.HolderWithdrawalStatisticsVO;
import com.baor.domain.WorkorderVO;
import com.baor.service.WorkorderService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WorkorderServiceImpl implements WorkorderService {
    @Autowired
    private WorkorderDao workorderDao;
    @Autowired
    private HolderWithdrawalStatisticsDao holderWithdrawalStatisticsDao;

    @Override
    public R workorderList(Map<String, Object> params) {
        try {
            // 1. 获取分页参数
            int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
            int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);

            // 2. 构建联表查询条件
            MPJLambdaWrapper<WorkorderVO> wrapper = new MPJLambdaWrapper<>();
            // 查询withdrawal_record表的所有字段
            wrapper.selectAll(WorkorderVO.class)
                    .select(CustomerVO::getNickname,CustomerVO::getPhone,CustomerVO::getId)
                    .select(EquipmentVO::getCode,EquipmentVO::getAddress)
                    .leftJoin(CustomerVO.class, CustomerVO::getId, WorkorderVO::getUserId)
                    .leftJoin(EquipmentVO.class, EquipmentVO::getId,WorkorderVO::getEquipmentId);
            // 3. 补充其他查询条件（保持原逻辑）
//            if (params.get("userid") != null && !params.get("userid").toString().isEmpty()) {
//                wrapper.eq(WorkorderVO::getUserId, params.get("userid"));
//            }

            if (params.get("organization") != null) {
                wrapper.like(CustomerVO::getOrganization, params.get("organization"));
            }
            if (params.get("code") != null) {
                wrapper.like(EquipmentVO::getCode, params.get("code"));
            }
            if (params.get("address") != null) {
                wrapper.like(EquipmentVO::getAddress, params.get("address"));
            }


//            if (params.get("status") != null) {
//                wrapper.eq(WorkorderVO::getStatus, params.get("status"));
//            }
//            if (params.get("applyTime") != null) {
//                wrapper.eq(WorkorderVO::getApplyTime, params.get("applyTime"));
//            }
            if (params.get("phone") != null) {
                wrapper.like(CustomerVO::getPhone, params.get("phone"));
            }
            if (params.get("nickname") != null) {
                wrapper.like(CustomerVO::getNickname, params.get("nickname"));
            }

            // 时间区间搜索 - 开始时间
            if (params.get("startTime") != null && !params.get("startTime").toString().trim().isEmpty()) {
                wrapper.ge(WorkorderVO::getApplyTime, params.get("startTime").toString().trim());
            }
            // 时间区间搜索 - 结束时间
            if (params.get("endTime") != null && !params.get("endTime").toString().trim().isEmpty()) {
                wrapper.le(WorkorderVO::getApplyTime, params.get("endTime").toString().trim());
            }

            // 4. 执行分页联表查询
            IPage<Map<String, Object>> resultPage = workorderDao.selectJoinMapsPage(page, wrapper);
            // 5. 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultPage.getRecords()); // 每条记录包含提现信息+username
            result.put("totalSize", resultPage.getTotal());
//            result.put("pages", resultPage.getPages());
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询失败: " + e.getMessage());
        }
    }
    //对提现状态进行修改（设备持
    @Override
    public R withdrawalInformation(Map<String, Object> params) {
        try {
            // 1. 获取参数
            Long id = Long.parseLong(params.get("id").toString()); // 提现记录ID
            Integer status = Integer.parseInt(params.get("status").toString()); // 审核状态
            String note = params.get("note") != null ? params.get("note").toString() : ""; // 备注信息
            // 2. 根据ID查询记录是否存在
            WorkorderVO record = workorderDao.selectById(id);
            if (record == null) {
                return R.er("提现记录不存在");
            }
            // 3. 更新状态和备注
            record.setStatus(status);
            record.setNote(note);
            // 4. 执行更新
            int updateCount = workorderDao.updateById(record);
            if (updateCount > 0) {
                return R.ok("审核状态更新成功");
            } else {
                return R.er("审核状态更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("参数错误或系统异常");
        }
    }
    @Override
    public R withdrawhistory(Map<String, Object> params) {
        try {
            // 1. 获取分页参数，默认第一页，每页10条
            int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
            int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            // 2. 构建分页对象
            Page<WorkorderVO> page = new Page<>(pageIndex, pageSize);
            // 3. 构建查询条件：状态非0（已审核的记录）
            MPJLambdaWrapper<WorkorderVO> wrapper = new MPJLambdaWrapper<>();
            wrapper.selectAll(WorkorderVO.class)
                    .select(CustomerVO::getNickname,CustomerVO::getPhone,CustomerVO::getIsHolder)
                    .leftJoin(CustomerVO.class, CustomerVO::getId, WorkorderVO::getUserId);
//            queryWrapper.ne("status", 0); // status != 0
//            queryWrapper.orderByDesc("apply_time"); // 按申请时间倒序排列
            if (params.get("applyTime") != null) {
                wrapper.eq(WorkorderVO::getApplyTime, params.get("applyTime"));
            }
            if (params.get("phone") != null) {
                wrapper.eq(CustomerVO::getPhone, params.get("phone"));
            }
            if (params.get("nickname") != null) {
                wrapper.eq(CustomerVO::getNickname, params.get("nickname"));
            }
            // 时间区间搜索 - 开始时间
            if (params.get("startTime") != null && !params.get("startTime").toString().trim().isEmpty()) {
                wrapper.ge(WorkorderVO::getApplyTime, params.get("startTime").toString().trim());
            }
            // 时间区间搜索 - 结束时间
            if (params.get("endTime") != null && !params.get("endTime").toString().trim().isEmpty()) {
                wrapper.le(WorkorderVO::getApplyTime, params.get("endTime").toString().trim());
            }
            if (params.get("is_holder") != null) {
                wrapper.eq(CustomerVO::getIsHolder, params.get("is_holder"));
                System.out.println(params.get("is_holder"));
            }
            // 4. 执行分页查询
            IPage<WorkorderVO> resultPage = workorderDao.selectPage(page, wrapper);
            // 5. 封装分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultPage.getRecords());
            result.put("totalSize", resultPage.getTotal());
//            result.put("pages", resultPage.getPages());
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询提现历史失败: " + e.getMessage());
        }
    }

    @Override
    public R WithdrawalLog(Map<String, Object> params){
        try {
            // 1. 获取分页参数，默认第一页，每页10条
            int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
            int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            // 2. 构建分页对象
            Page<WorkorderVO> page = new Page<>(pageIndex, pageSize);
            // 3. 构建查询条件：状态非0（已审核的记录）
            MPJLambdaWrapper<WorkorderVO> wrapper = new MPJLambdaWrapper<>();
            wrapper.select(WorkorderVO::getId, WorkorderVO::getStatus, WorkorderVO::getNote, WorkorderVO::getApplyTime)
                    .select(CustomerVO::getNickname)
                    .leftJoin(CustomerVO.class, CustomerVO::getId, WorkorderVO::getUserId);

            if (params.get("nickname") != null) {
                wrapper.eq(CustomerVO::getNickname, params.get("nickname"));
            }

            // 4. 执行分页查询
            IPage<WorkorderVO> resultPage = workorderDao.selectPage(page, wrapper);
            // 5. 封装分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultPage.getRecords());
            result.put("totalSize", resultPage.getTotal());
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询后台日志失败: " + e.getMessage());
        }
    }

    /**
     *持有人提现统计
     */
    @Override
    public R HWithdrawalStatistics(Map<String, Object> params) {
        try {
            int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
            int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            // 2. 构建分页对象
            Page<HolderWithdrawalStatisticsVO> page = new Page<>(pageIndex, pageSize);
            // 3. 构建查询条件：状态非0（已审核的记录）
            MPJLambdaWrapper<HolderWithdrawalStatisticsVO> wrapper = new MPJLambdaWrapper<>();
            wrapper.selectAll(HolderWithdrawalStatisticsVO.class);
//                    .eq(CustomerVO::getIsHolder, params.get("is_holder"));
//                    .leftJoin(CustomerVO.class, CustomerVO::getId, WorkorderVO::getUserId);

            IPage<HolderWithdrawalStatisticsVO> resultPage = holderWithdrawalStatisticsDao.selectPage(page, wrapper);
            // 5. 封装分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultPage.getRecords());
            result.put("totalSize", resultPage.getTotal());
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);
            return R.ok(result);

        } catch (Exception e){
            e.printStackTrace();
            return R.er("查询持有人提现统计失败："+e.getMessage());
        }
    }
}